import { getAddressList, getOrderInfo, submitOrderInfo, clearGoods } from "../../utils/requestApi.js";
import { toPay } from '../../utils/util.js'; 

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {  
    imgurl: app.data.imgurl,
    express: ['顺丰', '圆通', '中通', '韵达'],
    expressVal: '', // 快递值
    defaultAddressData: null,
    orderInfo: null,  //商品列表
    totalPrice: 0, //商品总价
    hiddenPay: true,  //支付modal
    payType: false, // 选择支付类型
    couponList: null,  //优惠券 
    goodsInfo: null, // url 携带的信息
  },

  onLoad: function (opt) {
    if (opt.obj) this.setData({ goodsInfo: JSON.parse(opt.obj) })
    if (opt.sku) this.setData({ goodsInfo: opt.sku })
  },   

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    console.log(this.data.goodsInfo.orderType)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getdefaultAddress()
    wx.removeStorageSync('confirmation')
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  //打开地址页面
  goaddress: function () {
    wx.setStorageSync('confirmation', true)
    wx.navigateTo({
      url: '../receivingAddress/receivingAddress',
    })
  },
  
  //获取地址  shippingId
  getdefaultAddress() {
    getAddressList().then(res => {
      if (res.data.Status == "Success" && res.data.Data != '[]') {
        if (wx.getStorageSync('shippingId')) {
          res.data.Data.forEach(item => {
            if (item.ShippingId == wx.getStorageSync('shippingId')) this.setData({ defaultAddressData: item })
          })
          wx.removeStorageSync('shippingId')
        } else this.setData({ defaultAddressData: res.data.Data[0] })
      } else this.setData({ defaultAddressData: null })
      this.initData()
    })
  },
  
  //初始化页面数据
  initData:function(){
    let { fromPage, buyAmount } = this.data;
    wx.showLoading({ title: '加载中...' })
    let { goodsInfo } = this.data;
    console.log(goodsInfo)
    getOrderInfo({
      orderType: goodsInfo.orderType ? goodsInfo.orderType : 'NormalOrder',
      productSku: goodsInfo.productSku ? goodsInfo.productSku : goodsInfo, // 商品规格 
      fromPage: goodsInfo.fromPage, // 活动（详情见备注）
      buyAmount: goodsInfo.buyAmount, // 购买数量
    }).then(res =>{
      if (res.data.Status == 'Success'){
        wx.hideLoading();
        if (res.data.Data.GiftItems.length != 0) {
          res.data.Data.GiftItems.forEach(item => { //礼品订单
            item.MemberPrice = item.NeedPrice
          })
        }
        this.setData({ orderInfo: res.data.Data })
      }
    })
    
  },

  //确认订单
  submintOrder:function(){
    let { defaultAddressData, goodsInfo, orderInfo } = this.data;
    if (!this.data.defaultAddressData) wx.showToast({ icon: 'none', title: '请填写收货地址' })
    if (goodsInfo.changeType == 1 || goodsInfo.orderType == 'NormalOrder' || typeof goodsInfo == 'string') wx.showLoading({ title: '提交订单中...' })
    submitOrderInfo({
      OrderSource: 8,
      shippingId: defaultAddressData.ShippingId,
      productSku: goodsInfo.productSku ? goodsInfo.productSku : goodsInfo,
      fromPage: goodsInfo.fromPage,
      buyAmount: goodsInfo.buyAmount,
      orderType: goodsInfo.orderType ? goodsInfo.orderType : 'NormalOrder',
    }).then(res =>{
      wx.hideLoading();
      if (res.data.Status == "Success") {
        let { OrderTotal, OrderId, Message, CellPhone } = res.data;
        if (typeof goodsInfo == 'string') clearGoods({ SkuIDs: goodsInfo, Source: 2 })
        let myParams = {
          message: Message,
          total: OrderTotal,
          id: OrderId,
          phone: CellPhone,
          point: orderInfo.GiftItems.length != 0 ? orderInfo.GiftItems[0].NeedPoint : '',
          orderType: goodsInfo.orderType ? goodsInfo.orderType : 'NormalOrder',
        }
        if (goodsInfo.changeType == 1 || goodsInfo.orderType == 'NormalOrder' || typeof goodsInfo == 'string'){  // 纯积分下单
          wx.navigateTo({ url: `../paySuccess/paySuccess?orderInfo=${JSON.stringify(myParams)}` })
        } else {  // 积分+金额下单   金额下单
          toPay(OrderId, res => {
            wx.navigateTo({ url: `../paySuccess/paySuccess?orderInfo=${JSON.stringify(myParams)}` })
          }, res =>{
            wx.navigateTo({ url: `/pages/orderDetail/orderDetail?id=${OrderId}` })
          })
        }        
      } else wx.showToast({ icon: 'none', title: res.data.Message })
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})